package com.socket.server;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

public class MyTextEncoder implements ProtocolEncoder{
    @Override
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
        String s = null;
        if (message instanceof String){
            s = (String) message;
        }
        if (s != null){
            CharsetEncoder charsetEncoder = (CharsetEncoder) session.getAttribute("encoder");
                    if (charsetEncoder == null){

                       charsetEncoder = Charset.defaultCharset().newEncoder();
                        session.setAttribute("encoder",charsetEncoder);
                    }
           IoBuffer ioBuffer =  IoBuffer.allocate(s.length()); //开辟内存
            ioBuffer.setAutoExpand(true); //自动扩展
            ioBuffer.putString(s,charsetEncoder);
            ioBuffer.flip();
            out.write(ioBuffer);

        }
    }

    @Override
    public void dispose(IoSession session) throws Exception {


    }
}
